<template>
  <n-card class="adv-product-check" :header-style="{ padding: '10px', background: '#F1F5FF', marginBottom: '10px' }"
    ref="elementRef">

    <template #header>
      <div class="flex items-center">
        <n-text style="width: 160px">{{ index }}.选择商品库</n-text>
        <div style="width: calc(100% - 160px)">
          <n-tabs @update:value="changeAccountCode" :value="currentMdmAccountCode" type="card" size="small"
            tab-style="min-width: 80px;" style="">
            <template v-if="radioValue == 1">
              <n-tab-pane v-for="(item, i) in accountList" :key="item.uuid" :tab="item.accountCode"
                :name="item.accountCode">
              </n-tab-pane></template>
            <template #suffix>
              <n-radio-group :value="radioValue" name="radioValue" @update:value="handleRadio">
                <n-radio-button :value="1">媒体账户</n-radio-button>
                <n-radio-button :value="2" :disabled="accountList.length <= 1">全账户相同</n-radio-button>
              </n-radio-group>
            </template>
          </n-tabs>
        </div>
      </div>
    </template>
    <div style="min-height: 350px" class="">
      <n-empty description="请先至少选择一个账户" style="margin-top: 100px" v-if="!accountList.length">

      </n-empty>
      <div v-show="accountList.length">
        <x-form ref="formRef" v-model:model="currentProduction" size="small" label-placement="left" wrap>
          <!--  -->
          <div class="search-box">
            <!-- 全账户相同的时候 -->
            <n-space vertical>
              <div v-if="radioValue === 2" class="align-center">
                <div class="form-item-label">
                  <text class="form-item-label__text" style="width: 160px;">主体名称</text>
                </div>

                <n-select style="max-width: 480px;" v-model:value="currentMdmId" :options="mdmSortAccounts"
                  value-field="id" label-field="name" filterable clearable @update:value="changeMdn" />
              </div>
              <div v-if="radioValue === 2" class="align-center">
                <div class="form-item-label">
                  <text class="form-item-label__text" style="width: 160px;">账户名称</text>
                </div>
                <n-select style="max-width: 480px;" v-model:value="currentMdmAccountCode" :options="currentMdnAccounts"
                  value-field="accountCode" label-field="accountCode" filterable clearable
                  @update:value="getCatalogsList" />
              </div>
              <!--  -->
              <div class="align-center" v-if="currentProduction">
                <div class="form-item-label">
                  <text class="form-item-label__text" style="width: 160px;">商品库选择</text>
                </div>

                <n-select :key="currentMdmAccountCode" style="max-width: 480px;"
                  v-model:value="currentProduction.productCatalogId" placeholder="请选择商品库" :options="catalogsList"
                  value-field="productCatalogId" label-field="productCatalogName" filterable clearable
                  @update:value="onChange" @click="getCatalogsList" />
              </div>
              <div class="align-center">
                <div class="form-item-label">
                  <text class="form-item-label__text" style="width: 160px;">选择商品库商品</text>
                </div>
                <n-input style="max-width: 480px;" v-model:value="keyword" placeholder="请输入商品名称/ID搜索商品" clearable
                  @keyup.enter="getProductItemsList" @input="handleSearch" />
              </div>
            </n-space>
          </div>
          <n-form-item label="选择账户" :show-label="false" path="productId" :rule="productRule" style="width: 100%"
            label-width="0">
            <!--  商品选择 -->


            <div class="flex flex-1">
              <div v-if="loading" class="flex-1">
                <n-skeleton :repeat="8" text></n-skeleton>
              </div>

              <div v-show="!loading" class="product-list" style="overflow: auto">
                <div class='flex items-center center' style="width: 100%;">
                  <n-empty description="暂无商品数据" v-if="!productList.length" style="margin-top: 30px">
                  </n-empty>
                </div>

                <div v-for="(item, index) in productList" :key="index"
                  :class="['item', { selected: item.productOuterId === currentProduction.productId }]"
                  @click="handleCheckProduct(item)">
                  <span class="icon-select" v-if="item.productOuterId === currentProduction.productId">
                    <n-icon color="#fff" size="14" :component="CheckOutlined" />
                  </span>
                  <div class="product-image">
                    <n-image v-if="item.productImageUrl" fit="contain" style="width: 100%; height: 100%"
                      :src="item.productImageUrl" width="64" height="64">
                    </n-image>
                  </div>
                  <div class="product-info">
                    <div class="product-text bold" :title="item.productName">{{ item.productName }}</div>
                    <div class="product-text" :title="item.productOuterId">ID：{{ item.productOuterId }}</div>
                    <div v-if="item.productPrice" class="product-text">商品价格：¥{{ item.productPrice }}</div>
                    <template v-if="isLimitedProductLib">
                      <div v-if="item.bandingSpuId" class="sub-product">
                        <div class="product-text light">{{ item.bandingSpuName }}</div>
                        <div class="product-text light">ID：{{ item.bandingSpuId }}</div>
                      </div>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </n-form-item>

        </x-form>
      </div>
    </div>
  </n-card>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref, toRef, watch, watchEffect } from 'vue'
import { useStore } from '@/store'
import {
  NEmpty,
  NCard,
  NSpace,
  NTabs,
  NTabPane,
  NText,
  NSelect,
  NInput,
  NRadioGroup,
  NRadioButton,
  NFormItem,
  NImage,
  NSkeleton,
  useDialog,
  NIcon,
  useMessage
} from 'naive-ui'
import { XForm, XButton, XDataTable } from '@/components';
import { getCatalogsList as getCatalogsListApi, getCatalogsProductList } from '@/api/intelligent';
import { CheckOutlined } from '@vicons/antd'
import Account from '@/store/modules/adv/account';
defineProps({
  index: {
    type: Number
  }
})

const store = useStore()
const dialog = useDialog()
const accountList = computed<any>(() => {
  return store.state.adv.accounts
})
const productLib = computed(() => store.state.adv.modal.productLib);


const mdmSortAccounts = computed(() => {
  const mdms: any = [];
  accountList.value.map((account: any) => {
    let mdm = mdms.find((mdm: any) => mdm.id === account.mdmName);
    if (!mdm) {
      mdm = {
        id: account.mdmName,
        accounts: [],
        name: account.mdmName
      }
      mdms.push(mdm)
    }
    mdm.accounts.push(account);
  })
  return mdms;
});

const currentMdmId = ref(null);

const currentMdnAccounts = computed(() => {
  return (mdmSortAccounts.value.find(_ => _.id === currentMdmId.value) || {}).accounts || []
})
const currentMdmAccountCode = ref(accountList.value[0] ? accountList.value[0].accountCode : undefined);

async function changeAccountCode(v) {
  currentMdmAccountCode.value = v;
  await getCatalogsList();
  // 获取商品库
  await getCatalogsList();
  if (!currentProduction.value.productCatalogId) {
    currentProduction.value.productCatalogId = (catalogsList.value[0] as any) ? catalogsList.value[0].productCatalogId : undefined;
  }
  getProductItemsList();

}
const safeAccount = new Account({});
const currentAccount = computed(() => {
  const account = accountList.value.find((_: any) => _.accountCode == currentMdmAccountCode.value && currentMdmAccountCode.value) || safeAccount
  return account;
});

const currentProduction = computed(() => (currentAccount.value && currentAccount.value.market.productInfo) || {});

const productRule = ref({
  trigger: 'input',
  validator(rule: any, value: any) {
    const unSetAccount = accountList.value.find(_ => _.market.productInfo && !_.market.productInfo.productId);
    if (unSetAccount) {
      currentMdmAccountCode.value = unSetAccount.accountCode;

      return new Error(radioValue.value == 2 ? `请选择商品!`: `请选择${unSetAccount.accountCode}账户的商品!`)
    }
    return true;

  }
})

const controlAccounts = toRef(store.state.adv, 'accounts');
watch(controlAccounts, (p, c) => {
  // console.log(controlAccounts, 'controlAccounts');
  // if (p.length == c.length) return;
  currentMdmAccountCode.value = accountList.value.length ? accountList.value[0].accountCode : undefined;
  if (currentMdmAccountCode.value) {
    getCatalogsList();
  }

})




const catalogsList = ref([])
const productList = ref<any>([])
const keyword = ref('')
const loading = ref(false)
const isLimitedProductLib = computed(() => {
  return currentProductTypeItem.value && currentProductTypeItem.value.bandingSpuFlag === 1
})
const currentProductTypeItem = computed<any>(() => {
  return catalogsList.value.find((v: any) => v.productCatalogId === currentProduction && currentProduction.value.productType)
})


const radioValue = ref(1)
onMounted(() => {
  getCatalogsList()
})


function changeMdn() {
  const accounts = currentMdnAccounts.value;
  if(accounts && accounts.length) {
    changeAccountCode(accounts[0].accountCode);
  }

}



const getCatalogsList = async () => {
  if (!accountList.value.length) return;
  const { data } = await getCatalogsListApi({
    accountCode: currentAccount.value.accountCode
  })
  catalogsList.value = data || [];

}

const onChange = (v) => {
  (currentProduction.value.productCatalogId = v);
  getProductItemsList()
}
const getProductItemsList = async () => {
  if (!accountList.value.length) return;

  const params = {
    productCatalogId: currentProduction.value.productCatalogId,
    accountCode: currentMdmAccountCode.value,
    keyword: keyword.value
  }
  loading.value = true;

  const { data } = await getCatalogsProductList(params)
  loading.value = false
  productList.value = data || []
}
const oldTime = ref<any>(null)
const handleSearch = () => {
  if (oldTime.value) {
    clearTimeout(oldTime.value)
  }
  oldTime.value = setTimeout(() => {
    getProductItemsList()
  }, 600)
}
const handleCheckProduct = (item: any) => {
  currentProduction.value.productId = item.productOuterId;
  if (radioValue.value == 2) {
    accountList.value.map(_ => {
      // console.log(_.market, 'market');
      _.market.productInfo.productId = item.productOuterId;
      _.market.productInfo.productCatalogId = currentProduction.value.productCatalogId
    })
  }
}
const handleRadio = (v: any) => {
  if (v === 2) {
    radioValue.value = 1;
    catalogsList.value = [];
    productList.value = [];
    currentMdmAccountCode.value = undefined;
    dialog.warning({
      title: '警告',
      content: '使用全账户相同，需将所有账户所处于一个业务单元中,否则将会搭建失败是否继续?',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        radioValue.value = 2;
        accountList.value.map((_: any) => {
          _.market.productInfo.productId = undefined;
          _.market.productInfo.productCatalogId = undefined;
        })
        if (mdmSortAccounts.value.length) {
          currentMdmId.value = mdmSortAccounts.value[0].id;
          currentMdmAccountCode.value = mdmSortAccounts.value[0].accounts[0] ? mdmSortAccounts.value[0].accounts[0].accountCode : undefined;
          changeAccountCode(currentMdmAccountCode.value);
        }
      },
      onNegativeClick: () => {
        radioValue.value = 1
      }
    })
  } else {
    dialog.warning({
      title: '警告',
      content: '使用媒体账户, 将会清空已经选择的商品库(需要重新选择),否则将会搭建失败是否继续?',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        accountList.value.map((_: any) => {
          _.market.productInfo.productId = undefined;
          _.market.productInfo.productCatalogId = undefined;
        })
        radioValue.value = 1;
        currentMdmAccountCode.value = accountList.value[0].accountCode;
        changeAccountCode(currentMdmAccountCode.value);
      },
      onNegativeClick: () => {
        radioValue.value = 2;
      }
    })


  }
}
const formRef = ref();
const elementRef = ref();
function validate() {
  return new Promise<void>((resolve, reject) => {
    formRef.value?.validate(async (errors: any) => {
      if (!errors) {
        try {
          resolve()
        } catch (e) {
          reject();
          store.commit('adv/SCROLL_TO_ELEMENT', elementRef.value.$el)
        }
      } else {
        store.commit('adv/SCROLL_TO_ELEMENT', elementRef.value.$el)
        reject()
      }
    })
  })
}


function defaultAction() {
  nextTick(async () => {
    const account = accountList.value[0];
    if (account) {
      // 选择首个账户
      currentMdmAccountCode.value = account.accountCode;
      // 获取商品库
      await getCatalogsList();
      if (!currentProduction.value.productCatalogId) {
        currentProduction.value.productCatalogId = catalogsList.value[0] ? catalogsList.value[0].productCatalogId : undefined;
      }
      getProductItemsList();
    }

  })

}

function getBackDisplay() {
  getProductItemsList()
}

defineExpose({
  validate,
  getBackDisplay,
  defaultAction
})
</script>
<style lang="scss">
.adv-product-check {
  .n-tabs .n-tabs-nav.n-tabs-nav--card-type .n-tabs-tab {
    background-color: #fff;
  }
}
</style>
<style lang="scss" scoped>
@import '@/assets/styles/var.scss';

.search-box {
  //display: grid;
  //grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  //gap: 10px;
  margin-bottom: 10px;
}

.product-list {
  width: 100%;
  display: flex;
  white-space: nowrap;
  flex-wrap: wrap;
  // grid-template-columns: repeat(auto-fit, minmax(1fr, 360px));
  gap: 10px;
  max-height: 300px;

  .item {
    display: flex;
    border-radius: 6px;
    padding: 6px 12px;
    width: 48%;
    cursor: pointer;
    border: 1px solid #ebeef5;
    background-color: #f5f6f8;

    &:hover {
      background-color: #f5f7fa;
    }

    .icon-select {
      position: absolute;
      top: 0;
      right: 0;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-items: center;
      background-color: $primaryColor;
      text-align: center;
      justify-content: center;
      border-radius: 0 0 0 4px;
    }

    &.selected {
      position: relative;
      // background-color: #ffefee;
      border: 1px solid $primaryColor;
    }

    .product-image {
      flex: none;
      width: 60px;
      height: 60px;
      border-radius: 4px;
      overflow: hidden;
      margin-right: 6px;

      .product-icon {
        font-size: 40px;
        line-height: 60px;
        color: #666666;
        text-align: center;
        display: block;
      }
    }

    .product-info {
      flex: 1;
      min-width: 120px;
      font-size: 12px;

      .sub-product {
        margin-top: 5px;

      }

      .product-text {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        line-height: 1.2em;
        margin-bottom: 8px;
        margin-top: 4px;

        &.light {
          color: #666666;
        }

        &.bold {
          font-weight: bold;
        }
      }
    }
  }
}
</style>
